/**
 * 保养工单 - 详情
 */

import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import {
    Typography,
    Card,
    Modal,
    Form,
    Row,
    Col,
    Input,
    TreeSelect,
    Button,
    DatePicker,
    InputNumber,
    Radio,
    Spin,
    message,
    Select,
} from 'antd';
import moment from 'moment';

import { get, post } from '../../axios/http';
import { BasicTable, formatTime } from '../../utils/x.js';

import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
const { Title } = Typography;
const { TextArea } = Input;
const { Option } = Select;


/**
 * 工单表单 - 保养部位 - 编辑表单
 */
const MaintenanceWorkOrderDetailForm3 = React.forwardRef(function MaintenanceWorkOrderDetailForm3({ form, form: { getFieldDecorator } }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    return (
        <Form>
            <Form.Item label="保养部位">
                {getFieldDecorator("positionName")(
                    <Input disabled />
                )}
            </Form.Item>
            <Form.Item label="状态">
                {getFieldDecorator("status")(
                    <Radio.Group>
                        <Radio value={0}>不正常</Radio>
                        <Radio value={1}>正常</Radio>
                    </Radio.Group>
                )}
            </Form.Item>
            <Form.Item label="备注">
                {getFieldDecorator("remarks")(
                    <Input />
                )}
            </Form.Item>
            {getFieldDecorator("id")(
                <Input type="hidden" />
            )}
            {getFieldDecorator("requirementId")(
                <Input type="hidden" />
            )}
            {getFieldDecorator("maintain")(
                <Input type="hidden" />
            )}
            {getFieldDecorator("maintainStandard")(
                <Input type="hidden" />
            )}
        </Form>
    );
});

/**
 * 工单表单 - 保养部位 - 选择表格
 */
function MaintenanceWorkOrderDetailTable5({ selectedKeys, onSelectChange }) {
    const [data, setData] = useState([]);
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [table1Pagination, setTable1Pagination] = useState({});

    const tableColumns = [
        {
            title: '设备类型',
            dataIndex: 'equType',
        },
        {
            title: '保养部位',
            dataIndex: 'equMaintainPart',
        },
        {
            title: '保养标准',
            dataIndex: 'equMaintainStandard',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findMaintainPositionDetails', { params: dataQuery });
                setData(res.data);
                setTable1Pagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <BasicTable
            rowKey="id"
            dataSource={data}
            columns={tableColumns}
            rowSelection={tableRowSelection}
            loading={isDataLoading}
            pagination={table1Pagination} />
    );
}

/**
 * 工单表单 - 保养部位表格
 */
function MaintenanceWorkOrderDetailTable4({ data, mode, onEvent }) {
    const handleEditClick = useCallback((e) => {
        e.preventDefault();
        const data = e.currentTarget.getAttribute('data-data');
        onEvent({ type: 'EDIT_ITEM', data: JSON.parse(data) });
    }, []);

    const handleDeleteClick = useCallback((e) => {
        e.preventDefault();
        const index = Number(e.currentTarget.getAttribute('data-index'));
        Modal.confirm({
            title: '确认删除该用户？',
            onOk() {
                onEvent({ type: 'DELETE_ITEM', index });
            },
        });
    }, []);

    const tableColumns = [
        {
            title: '保养部位',
            dataIndex: 'positionName',
        },
        {
            title: '保养标准',
            dataIndex: 'maintainStandard',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (text) => {
                switch (text) {
                    case 0:
                        return '不正常';
                    case 1:
                        return '正常';
                }
            },
        },
        {
            title: '备注',
            dataIndex: 'remarks',
        },
        {
            title: '操作',
            render: (text, record, index) => {
                return (
                    <>
                        <a href="#" style={{ marginRight: 10 }} data-data={JSON.stringify(record)} onClick={handleEditClick}>编辑</a>
                        {mode === 'add' && <a href="#" data-index={index} onClick={handleDeleteClick}>删除</a>}
                    </>
                );
            }
        }
    ];

    return (
        <BasicTable
            dataSource={data}
            columns={tableColumns} />
    );
}

/**
 * 工单表单 - 保养工作量 - 编辑表单
 */
const MaintenanceWorkOrderDetailForm2 = React.forwardRef(function MaintenanceWorkOrderDetailForm2({ form, form: { getFieldDecorator, getFieldValue, setFieldsValue } }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    const handleStartTimeChange = useCallback((date) => {
        const endTime = getFieldValue('maintainEndTime');
        if (!endTime || date > endTime) {
            setFieldsValue({
                wastedTime: null,
            });
            return;
        }
        const m = Math.floor((endTime - date) / 1000 / 60);
        setFieldsValue({
            wastedTime: `${Math.floor(m / 60)}小时${m % 60}分`,
        });
    }, []);

    const handleEndTimeChange = useCallback((date) => {
        const startTime = getFieldValue('maintainStartTime');
        if (!startTime || startTime > date) {
            setFieldsValue({
                wastedTime: null,
            });
            return;
        }
        const m = Math.floor((date - startTime) / 1000 / 60);
        setFieldsValue({
            wastedTime: `${Math.floor(m / 60)}小时${m % 60}分`,
        });
    }, []);

    return (
        <Form>
            <Form.Item label="姓名">
                {getFieldDecorator("userName")(
                    <Input readOnly />
                )}
            </Form.Item>
            <Form.Item label="保养开始时间">
                {getFieldDecorator("maintainStartTime")(
                    <DatePicker showTime onChange={handleStartTimeChange} />
                )}
            </Form.Item>
            <Form.Item label="保养结束时间">
                {getFieldDecorator("maintainEndTime")(
                    <DatePicker showTime onChange={handleEndTimeChange} />
                )}
            </Form.Item>
            <Form.Item label="保养用时">
                {getFieldDecorator("wastedTime")(
                    <Input disabled />
                )}
            </Form.Item>
            <Form.Item label="内容或步骤">
                {getFieldDecorator("contentOrSteps")(
                    <Input />
                )}
            </Form.Item>
            <Form.Item style={{ marginBottom: 0 }}>
                {getFieldDecorator("id")(
                    <Input type="hidden" />
                )}
            </Form.Item>
            <Form.Item style={{ marginBottom: 0 }}>
                {getFieldDecorator("personId")(
                    <Input type="hidden" />
                )}
            </Form.Item>
        </Form>
    );
});

/**
 * 工单表单 - 保养工作量表格
 */
function MaintenanceWorkOrderDetailTable3({ data, mode, onEvent }) {
    const handleEditClick = useCallback((e) => {
        e.preventDefault();
        const data = e.currentTarget.getAttribute('data-data');
        onEvent({ type: 'EDIT_USER', data: JSON.parse(data) });
    }, []);

    const handleDeleteClick = useCallback((e) => {
        e.preventDefault();
        const index = Number(e.currentTarget.getAttribute('data-index'));
        Modal.confirm({
            title: '确认删除该用户？',
            onOk() {
                onEvent({ type: 'DELETE_USER', index });
            },
        });
    }, []);

    const tableColumns = [
        {
            title: '姓名',
            dataIndex: 'userName',
        },
        {
            title: '保养开始时间',
            dataIndex: 'maintainStartTime',
            render: (text, row, index) => {
                return (text && text.format) ? text.format('YYYY-MM-DD HH:mm:ss') : text;
            },
        },
        {
            title: '保养结束时间',
            dataIndex: 'maintainEndTime',
            render: (text, row, index) => {
                return (text && text.format) ? text.format('YYYY-MM-DD HH:mm:ss') : text;
            },
        },
        {
            title: '保养用时',
            dataIndex: 'wastedTime',
        },
        {
            title: '内容或步骤',
            dataIndex: 'contentOrSteps',
        },
        {
            title: '操作',
            render: (text, record, index) => {
                return (
                    <>
                        <a href="#" style={{ marginRight: 10 }} data-data={JSON.stringify(record)} onClick={handleEditClick}>编辑</a>
                        <a href="#" data-index={index} onClick={handleDeleteClick}>删除</a>
                    </>
                );
            }
        }
    ];

    return (
        <BasicTable
            rowKey="personId"
            dataSource={data}
            columns={tableColumns} />
    );
}

/**
 * 工单表单 - 选择人员 - 搜索表单
 */
function MaintenanceWorkOrderDetailTable2SearchForm({ form, form: { getFieldDecorator }, onSubmit, treeData2, treeData6 }) {
    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    const emptyItem = { title: '全部', value: null };

    return (
        <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 10 }}>
            <Form.Item label="用户名称">
                {getFieldDecorator('userName')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="执行班组">
                {getFieldDecorator('team')(
                    <TreeSelect treeData={[emptyItem, ...treeData6]} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item label="使用部门">
                {getFieldDecorator('department')(
                    <TreeSelect treeData={[emptyItem, ...treeData2]} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 工单表单 - 保养工作量表格
 */
function MaintenanceWorkOrderDetailTable2({ selectedKeys, onSelectChange, treeData2, treeData6 }) {
    const [data, setData] = useState([]);
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [table1Pagination, setTable1Pagination] = useState({});

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'userName',
        },
        {
            title: '职务',
            dataIndex: 'roleName',
        },
        {
            title: '部门',
            dataIndex: 'department',
        },
        {
            title: '执行班组',
            dataIndex: 'teamName',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    const fetchData = useCallback((params = {}, exact = false) => {
        setDataQuery(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const SearchFormWrap = useMemo(() => {
        return Form.create()(MaintenanceWorkOrderDetailTable2SearchForm);
    }, [treeData2, treeData6]);

    const handleSearchFormSubmit = useCallback((values) => {
        fetchData(values, true);
    }, []);

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findUserOfMaintain', { params: dataQuery });
                setData(res.data);
                setTable1Pagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <SearchFormWrap onSubmit={handleSearchFormSubmit} treeData2={treeData2} treeData6={treeData6} />
            <BasicTable
                rowKey="id"
                dataSource={data}
                columns={tableColumns}
                rowSelection={tableRowSelection}
                loading={isDataLoading}
                pagination={table1Pagination} />
        </>
    );
}

/**
 * 工单表单 - 选择设备 - 搜索表单
 */
function MaintenanceWorkOrderDetailTable1SearchForm({ form, form: { getFieldDecorator }, onSubmit, treeData1, treeData2 }) {
    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    const treeData1Extra = [
        {
            title: '全部',
            value: null,
        },
        ...treeData1,
    ];
    const treeData2Extra = [
        {
            title: '全部',
            value: null,
        },
        ...treeData2,
    ];

    return (
        <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 10 }}>
            <Form.Item label="搜索条件">
                {getFieldDecorator('quickSearch')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="设备类型">
                {getFieldDecorator('equTypeId')(
                    <TreeSelect treeData={treeData1Extra} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item label="使用部门">
                {getFieldDecorator('depId')(
                    <TreeSelect treeData={treeData2Extra} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 工单表单 - 选择设备 - 表格
 */
function MaintenanceWorkOrderDetailTable1({ selectedKeys, onSelectChange, treeData1, treeData2 }) {
    const [data, setData] = useState([]);
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [table1Pagination, setTable1Pagination] = useState({});

    const tableColumns = [
        {
            title: '设备编号',
            dataIndex: 'equCode',
        },
        {
            title: '设备名称',
            dataIndex: 'equName',
        },
        {
            title: '规格型号',
            dataIndex: 'equSpecsModel',
        },
        {
            title: '使用部门',
            dataIndex: 'department',
        },
        {
            title: '设备类型',
            dataIndex: 'equTypeName',
        },
    ];
    const tableRowSelection = {
        type: 'radio',
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    const fetchData = useCallback((params = {}, exact = false) => {
        setDataQuery(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const SearchFormWrap = useMemo(() => {
        return Form.create()(MaintenanceWorkOrderDetailTable1SearchForm);
    }, [treeData1, treeData2]);

    const handleSearchFormSubmit = useCallback((values) => {
        const newValue = { ...values };
        if (newValue.quickSearch === '') {
            delete newValue.quickSearch;
        }
        fetchData(newValue, true);
    }, []);

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findEquipment', { params: dataQuery });
                setData(res.data);
                setTable1Pagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <SearchFormWrap onSubmit={handleSearchFormSubmit} treeData1={treeData1} treeData2={treeData2} />
            <BasicTable
                rowKey="id"
                dataSource={data}
                columns={tableColumns}
                rowSelection={tableRowSelection}
                loading={isDataLoading}
                pagination={table1Pagination} />
        </>
    );
}

/**
 * 工单表单
 */
const MaintenanceWorkOrderDetailForm1 = React.forwardRef(function MaintenanceWorkOrderDetailForm1({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue, getFieldsValue } }, ref) {
    const [modalMode, setModalMode] = useState();
    const [treeData1, setTreeData1] = useState([]); // 设备类型
    const [treeData2, setTreeData2] = useState([]); // 所在部门
    const treeData3 = [
        {
            value: 0,
            title: '保养中',
        },
        {
            value: 1,
            title: '已完成',
        },
        {
            value: 2,
            title: '待保养',
            disabled: true,
        },
    ]; // 保养状态
    const [treeData4, setTreeData4] = useState([]); // 保养级别
    const [treeData5, setTreeData5] = useState([]); // 外派单位
    const [treeData6, setTreeData6] = useState([]); // 保养班组

    const [isModal1Open, setIsModal1Open] = useState(false);
    const [selected1, setSelected1] = useState({ key: [], row: [] });
    const [isModal2Open, setIsModal2Open] = useState(false);
    const [selected2, setSelected2] = useState({ key: [], row: [] });
    const [isModal3Open, setIsModal3Open] = useState(false);
    const [modal3Data, setModal3Data] = useState({});
    const [isModal4Open, setIsModal4Open] = useState(false);
    const [selected5, setSelected5] = useState({ key: [], row: [] });
    const [isModal5Open, setIsModal5Open] = useState(false);
    const [modal5Data, setModal5Data] = useState({});

    const [isStatusDisabled, setIsStatusDisabled] = useState(false);

    const [workAddDTOList, setWorkAddDTOList] = useState([]);
    const [positionAddDTOList, setPositionAddDTOList] = useState([]);

    // 选择设备
    const handleSelectEquipmentClick = useCallback(() => {
        setSelected1({ key: [], row: [] });
        setIsModal1Open(true);
    }, []);

    const handleModal1SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected1({ key: selectedRowKeys, row: selectedRows });
    }, []);

    const handleModal1Ok = useCallback(() => {
        setFieldsValue({
            equipmentId: selected1.row[0].id,
            equipmentCode: selected1.row[0].equCode,
            equipmentName: selected1.row[0].equName,
            equipmentTypeId: selected1.row[0].equTypeID,
            equipmentSpecsModel: selected1.row[0].equSpecsModel,
            departmentId: selected1.row[0].departmentId,
        });
        setIsModal1Open(false);
    }, [selected1]);

    const handleModal1Cancel = useCallback(() => {
        setIsModal1Open(false);
    }, []);

    // 保养工作量
    const handleSelectUserClick = useCallback(() => {
        setIsModal2Open(true);
    }, []);

    const handleModal2SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected2({ key: selectedRowKeys, row: selectedRows });
    }, []);

    const handleModal2Ok = useCallback(() => {
        setWorkAddDTOList(prev => {
            const newData = [...prev];
            const ids = newData.map(item => item.personId);
            selected2.row.forEach(item => {
                ids.indexOf(item.id) === -1 && newData.push({
                    id: null,
                    personId: item.id,
                    userName: item.userName,
                    maintainStartTime: '',
                    maintainEndTime: '',
                    wastedTime: '',
                    contentOrSteps: '',
                });
            });
            return newData;
        });
        setIsModal2Open(false);
    }, [selected2]);

    const handleModal2Cancel = useCallback(() => {
        setIsModal2Open(false);
    }, []);

    const handleTable3Event = useCallback((e) => {
        switch (e.type) {
            case 'DELETE_USER': {
                setWorkAddDTOList(prev => {
                    const newData = [...prev];
                    newData.splice(e.index, 1);
                    return newData;
                });
                break;
            }
            case 'EDIT_USER': {
                setModal3Data(e.data);
                setIsModal3Open(true);
                break;
            }
        }
    }, []);

    // 保养工作量 - 编辑保养人员
    const modal3FormRef = useRef();

    const handleModal3Ok = useCallback(() => {
        modal3FormRef.current.form.validateFields((err, values) => {
            if (err) {
                return;
            }
            setWorkAddDTOList(prev => {
                const newData = [...prev];
                const i = newData.findIndex(item => item.personId === values.personId);
                newData.splice(i, 1, values);
                return newData;
            });
            setIsModal3Open(false);
        });
    }, []);

    const handleModal3Cancel = useCallback(() => {
        setIsModal3Open(false);
    }, []);

    const Modal3Form = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            // isDebug && console.log(data);
            return (data && data.personId) ? {
                id: Form.createFormField({ value: data.id }),
                personId: Form.createFormField({ value: data.personId }),
                userName: Form.createFormField({ value: data.userName }),
                maintainStartTime: Form.createFormField({ value: data.maintainStartTime ? moment(data.maintainStartTime) : '' }),
                maintainEndTime: Form.createFormField({ value: data.maintainStartTime ? moment(data.maintainEndTime) : '' }),
                wastedTime: Form.createFormField({ value: data.wastedTime }),
                contentOrSteps: Form.createFormField({ value: data.contentOrSteps }),
            } : {};
        }
    })(MaintenanceWorkOrderDetailForm2);

    // 保养部位
    const handleSelectPositionClick = useCallback(() => {
        setIsModal4Open(true);
    }, []);

    const handleModal4Ok = useCallback(() => {
        setPositionAddDTOList(prev => {
            const newData = [...prev];
            const ids = newData.map(item => item.requirementId);
            selected5.row.forEach(item => {
                ids.indexOf(item.id) === -1 && newData.push({
                    id: null,
                    requirementId: item.id,
                    // positionName: item.positionName,
                    positionName: item.equMaintainPart,
                    // maintainStandard: item.maintainStandard,
                    maintainStandard: item.equMaintainStandard,
                    status: item.status || null,
                    maintain: item.maintain || null,
                    remarks: null,
                });
            });
            return newData;
        });
        setIsModal4Open(false);
    }, [selected5]);

    const handleModal4Cancel = useCallback(() => {
        setIsModal4Open(false);
    }, []);

    const handleTable4Event = useCallback((e) => {
        switch (e.type) {
            case 'DELETE_ITEM': {
                setPositionAddDTOList(prev => {
                    const newData = [...prev];
                    newData.splice(e.index, 1);
                    return newData;
                });
                break;
            }
            case 'EDIT_ITEM': {
                setModal5Data(e.data);
                setIsModal5Open(true);
                break;
            }
        }
    }, []);

    const handleTable5SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected5({ key: selectedRowKeys, row: selectedRows });
    }, []);

    // 保养部位 - 编辑部位
    const modal5FormRef = useRef();

    const handleModal5Ok = useCallback(() => {
        modal5FormRef.current.form.validateFields((err, values) => {
            if (err) {
                return;
            }
            setPositionAddDTOList(prev => {
                const newData = [...prev];
                const i = newData.findIndex(item => item.requirementId === values.requirementId);
                newData.splice(i, 1, values);
                return newData;
            });
            setIsModal5Open(false);
        });
    }, []);

    const handleModal5Cancel = useCallback(() => {
        setIsModal5Open(false);
    }, []);

    const Modal5Form = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            // console.log('modal5:', data);
            return (data && data.requirementId) ? {
                id: Form.createFormField({ value: data.id }),
                requirementId: Form.createFormField({ value: data.requirementId }),
                positionName: Form.createFormField({ value: data.positionName }),
                maintainStandard: Form.createFormField({ value: data.maintainStandard }),
                status: Form.createFormField({ value: data.status }),
                maintain: Form.createFormField({ value: data.maintain }),
                remarks: Form.createFormField({ value: data.remarks }),
            } : {};
        }
    })(MaintenanceWorkOrderDetailForm3);

    const handleStartTimeChange = useCallback((date) => {
        const endTime = getFieldValue('maintainEndTime');
        if (!endTime || date > endTime) {
            setFieldsValue({
                wastedTime: null,
            });
            return;
        }
        const m = Math.floor((endTime - date) / 1000 / 60);
        setFieldsValue({
            wastedTime: `${Math.floor(m / 60)}小时${m % 60}分`,
        });
    }, []);

    const handleEndTimeChange = useCallback((date) => {
        const startTime = getFieldValue('maintainStartTime');
        if (!startTime || startTime > date) {
            setFieldsValue({
                wastedTime: null,
            });
            return;
        }
        const m = Math.floor((date - startTime) / 1000 / 60);
        setFieldsValue({
            wastedTime: `${Math.floor(m / 60)}小时${m % 60}分`,
        });
    }, []);


    // 其它
    React.useImperativeHandle(ref, () => ({ form }));

    useEffect(() => {
        const parseDepData = (arr) => {
            const result = [];
            for (const item of arr) {
                result.push({
                    value: item.id,
                    title: item.name,
                    children: parseDepData(item.children),
                });
            }
            return result;
        };
        const parseWorkAddDtoListData = (arr) => {
            return arr.map(item => ({
                ...item,
                userName: item.personName,
            }));
        };

        // console.log('initData:', getFieldsValue());

        setWorkAddDTOList(parseWorkAddDtoListData(JSON.parse(getFieldValue('equipmentMaintainWorkAddDTOList'))));
        setPositionAddDTOList(JSON.parse(getFieldValue('equipmentMaintainPositionAddDTOList')));

        const mode = getFieldValue('id') ? 'edit' : 'add'
        setModalMode(mode);

        switch (mode) {
            case 'add': {
                (async () => {
                    try {
                        const res1 = await get(euqApplicationName + '/currency/queryEquipmentType');
                        setTreeData1(res1.data.map(item => {
                            return {
                                value: item.id,
                                title: item.name,
                            };
                        }));
                    } catch (err) {}
                })();
                break;
            }
            case 'edit': {
                const _data = getFieldValue('_data');
                _data.maintainStatus === 1 && setIsStatusDisabled(true);
                setTreeData1([
                    {
                        title: _data.equipmentType,
                        value: _data.equipmentTypeId,
                    }
                ]);
                setTreeData2([
                    {
                        title: _data.equipmentDepart,
                        value: _data.departmentId,
                    }
                ]);
                break;
            }
            default:
                break;
        }

        (async () => {
            try {
                // const res2 = await get(lotAuth + '/department/queryTreeDepartment');
                const res2 = await get(lotAuth2 + '/department/queryTreeDepartment');
                setTreeData2(parseDepData(res2.data));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res4 = await get(euqApplicationName + '/api/findEquipmentNextParameterPageList?typeId=6');
                setTreeData4(res4.data.map(item => {
                    return {
                        value: item.id,
                        title: item.configValue.trim(),
                    };
                }));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res5 = await get(euqApplicationName + '/parameter_setting_public/queryRentDepartmentList', { params: { type: 1 } });
                res5 && setTreeData5(res5.data.map(item => ({
                    value: item.id,
                    title: item.name,
                })));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res6 = await get(euqApplicationName + '/currency/queryTeam');
                setTreeData6(res6.data.map(item => {
                    return {
                        value: item.id,
                        title: item.name,
                    };
                }));
            } catch (err) {}
        })();
    }, []);

    useEffect(() => {
        setFieldsValue({
            equipmentMaintainWorkAddDTOList: JSON.stringify(workAddDTOList),
        });
    }, [workAddDTOList]);

    useEffect(() => {
        setFieldsValue({
            equipmentMaintainPositionAddDTOList: JSON.stringify(positionAddDTOList),
        });
    }, [positionAddDTOList]);

    return (
        <>
            <Form layout="horizontal" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                <Title level={4}>设备信息</Title>
                <Row>
                    <Col span={12}>
                        <Form.Item label="设备编号">
                            {getFieldDecorator("equipmentCode", {
                                rules: [
                                    {
                                        required: true,
                                    },
                                ],
                            })(<Input disabled />)}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="设备名称">
                            {getFieldDecorator("equipmentName", {
                                rules: [
                                    {
                                        required: true,
                                    },
                                ],
                            })(<Input disabled />)}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="设备类型">
                            {getFieldDecorator("equipmentTypeId")(
                                <TreeSelect treeData={treeData1} disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="规格型号">
                            {getFieldDecorator("equipmentSpecsModel")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="所在部门">
                            {getFieldDecorator("departmentId")(
                                <TreeSelect treeData={treeData2} disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={11} offset={1}>
                        <Button type="primary" disabled={modalMode !== 'add'} onClick={handleSelectEquipmentClick}>选择设备</Button>
                    </Col>
                    {getFieldDecorator("equipmentId")(
                        <Input type="hidden" />
                    )}
                </Row>

                <Title level={4}>处理情况</Title>
                <Row>
                    <Col span={12}>
                        <Form.Item label="保养班组">
                            {getFieldDecorator("maintainTeamId")(
                                <TreeSelect treeData={treeData6} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="保养状态">
                            {getFieldDecorator("maintainStatus", {
                                rules: [
                                    {
                                        required: true,
                                    },
                                ],
                            })(
                                <TreeSelect disabled={isStatusDisabled} treeData={treeData3} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="保养级别">
                            {getFieldDecorator("maintainLevel")(
                                <TreeSelect treeData={treeData4} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="外派单位">
                            {getFieldDecorator("outsource")(
                                <TreeSelect treeData={treeData5} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="开始时间">
                            {getFieldDecorator("maintainStartTime")(
                                <DatePicker showTime onChange={handleStartTimeChange} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="结束时间">
                            {getFieldDecorator("maintainEndTime")(
                                <DatePicker showTime onChange={handleEndTimeChange} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="保养用时">
                            {getFieldDecorator("wastedTime")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="保养费用">
                            {getFieldDecorator("maintainCost")(
                                <InputNumber />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="停机">
                            {getFieldDecorator("isStop", {
                                initialValue: 1,
                            })(
                                <Radio.Group>
                                    <Radio value={0}>停机</Radio>
                                    <Radio value={1}>不停机</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="停机时长">
                            {getFieldDecorator("shutdownDuration")(
                                <InputNumber disabled={getFieldValue('isStop') === 1} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item label="工作描述" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("workDescription")(
                                <TextArea rows={4} />
                            )}
                        </Form.Item>
                    </Col>

                    <Title level={4} style={{ marginTop: 10 }}>保养工作量</Title>
                    <Button type="primary" onClick={handleSelectUserClick}>增加人员</Button>
                    <MaintenanceWorkOrderDetailTable3 data={workAddDTOList} onEvent={handleTable3Event} />
                    {getFieldDecorator('equipmentMaintainWorkAddDTOList', {
                        initialValue: '[]',
                    })(
                        <Input type="hidden" />
                    )}

                    <Title level={4} style={{ marginTop: 10 }}>保养部位</Title>
                    <Button type="primary" disabled={modalMode !== 'add'} onClick={handleSelectPositionClick}>选择明细</Button>
                    <MaintenanceWorkOrderDetailTable4 data={positionAddDTOList} mode={modalMode} onEvent={handleTable4Event} />
                    {getFieldDecorator('equipmentMaintainPositionAddDTOList', {
                        initialValue: '[]',
                    })(<Input type="hidden" />)}

                    {getFieldDecorator('id', {
                        initialValue: null,
                    })(<Input type="hidden" />)}
                    {getFieldDecorator('maintainTreatmentId', {
                        initialValue: null,
                    })(<Input type="hidden" />)}
                </Row>
                {getFieldDecorator('_data', {
                    initialValue: {},
                })(
                    <Input type="hidden" />
                )}
            </Form>
            <Modal title="选择设备" width={880} visible={isModal1Open} onOk={handleModal1Ok} onCancel={handleModal1Cancel}>
                <MaintenanceWorkOrderDetailTable1 selectedKeys={selected1.key} onSelectChange={handleModal1SelectChange} treeData1={treeData1} treeData2={treeData2} />
            </Modal>
            <Modal title="选择人员" width={880} visible={isModal2Open} onOk={handleModal2Ok} onCancel={handleModal2Cancel}>
                <MaintenanceWorkOrderDetailTable2 selectedKeys={selected2.key} onSelectChange={handleModal2SelectChange} treeData2={treeData2} treeData6={treeData6} />
            </Modal>
            <Modal title="编辑人员" visible={isModal3Open} onOk={handleModal3Ok} onCancel={handleModal3Cancel}>
                <Modal3Form wrappedComponentRef={modal3FormRef} data={modal3Data} />
            </Modal>
            <Modal title="选择部位" width={640} visible={isModal4Open} onOk={handleModal4Ok} onCancel={handleModal4Cancel}>
                <MaintenanceWorkOrderDetailTable5 selectedKeys={selected5.key} onSelectChange={handleTable5SelectChange} />
            </Modal>
            <Modal title="编辑部位" visible={isModal5Open} onOk={handleModal5Ok} onCancel={handleModal5Cancel}>
                <Modal5Form wrappedComponentRef={modal5FormRef} data={modal5Data} />
            </Modal>
        </>
    );
});

/**
 * 主组件
 */
function MaintenanceWorkOrderDetail() {
    const { id } = useParams();
    const history = useHistory();

    const [mode, setMode] = useState('add');
    const [form1Data, setForm1Data] = useState({});
    const [isDataLoading, setIsDataLoading] = useState(true);

    const viewTitle = {
        add: '新增工单',
        edit: '保养工单',
    };

    // 表单1
    const form1Ref = useRef();
    const Form1Wrap = useMemo(() => {
        return Form.create({
            mapPropsToFields(props) {
                const { data } = props;
                // console.log('init:', data);
                return (data && data.id) ? {
                    id: Form.createFormField({ value: data.id }),
                    equipmentCode: Form.createFormField({ value: data.equipmentCode }),
                    equipmentName: Form.createFormField({ value: data.equipmentName }),
                    equipmentTypeId: Form.createFormField({ value: data.equipmentTypeId }),
                    equipmentSpecsModel: Form.createFormField({ value: data.equipmentSpecsModel }),
                    departmentId: Form.createFormField({ value: data.departmentId }),
                    equipmentId: Form.createFormField({ value: data.equipmentId }),
                    maintainTeamId: Form.createFormField({ value: data.maintainTeamId }),
                    maintainStatus: Form.createFormField({ value: data.maintainStatus }),
                    // maintainLevel: Form.createFormField({ value: data.maintainLevel }),
                    maintainLevel: Form.createFormField({ value: data.maintainLevelId }),
                    maintainTreatmentId: Form.createFormField({ value: data.maintainTreatmentId }),
                    outsource: Form.createFormField({ value: data.outSourceId }),
                    maintainStartTime: Form.createFormField({ value: data.maintainStartTime ? moment(data.maintainStartTime) : data.maintainStartTime }),
                    maintainEndTime: Form.createFormField({ value: data.maintainEndTime ? moment(data.maintainEndTime) : data.maintainEndTime }),
                    wastedTime: Form.createFormField({ value: data.wastedTime }),
                    maintainCost: Form.createFormField({ value: data.maintainCost }),
                    isStop: Form.createFormField({ value: data.isStop }),
                    shutdownDuration: Form.createFormField({ value: data.stopTime }),
                    // workDescription: Form.createFormField({ value: data.workDescription }),
                    workDescription: Form.createFormField({ value: data.description }),
                    equipmentMaintainWorkAddDTOList: Form.createFormField({ value: JSON.stringify(data.equipmentMaintainWorkVOList) }),
                    equipmentMaintainPositionAddDTOList: Form.createFormField({ value: JSON.stringify(data.equipmentMaintainPositionVOList) }),
                    _data: Form.createFormField({ value: data }),
                } : {}
            }
        })(MaintenanceWorkOrderDetailForm1);
    }, [form1Data]);


    // 其它
    const handleSubmitClick = useCallback(() => {
        (async () => {
            try {
                const values = await new Promise((resolve, reject) => {
                    form1Ref.current.form.validateFields((err, values) => {
                        if (err) {
                            message.error('表单验证错误');
                            reject();
                            return;
                        }
                        resolve(values);
                    });
                });

                const positionList = JSON.parse(values.equipmentMaintainPositionAddDTOList);
                const workList = JSON.parse(values.equipmentMaintainWorkAddDTOList);

                if (values.maintainStatus === 1) {
                    const currentTime = await getCurrentTime();
                    const currentMoment = moment(currentTime);

                    if (!values.maintainStartTime || !values.maintainEndTime) {
                        Modal.error({
                            content: '当状态为已完成时，必须填写开始时间和结束时间',
                        });
                        return;
                    }
                    if (currentMoment < moment(values.maintainEndTime)) {
                        Modal.error({
                            content: '当状态为已完成时，结束时间必须小于当前时间',
                        });
                        return;
                    }
                    if (workList.length === 0) {
                        workList.push({
                            id: null,
                            personId: Number(localStorage.getItem('userId')),
                            userName: localStorage.getItem('userName'),
                            maintainStartTime: formatTime(values.maintainStartTime),
                            maintainEndTime: formatTime(values.maintainEndTime),
                            wastedTime: values.wastedTime,
                            contentOrSteps: null,
                        });
                    } else {
                        for (const workItem of workList) {
                            if (!workItem.maintainStartTime || !workItem.maintainEndTime || moment(workItem.maintainStartTime) < values.maintainStartTime || moment(workItem.maintainEndTime) > values.maintainEndTime) {
                                Modal.error({
                                    content: '当状态为已完成时，保养人员的开始时间和结束时间必须介于工单的开始时间和结束时间之间',
                                });
                                return;
                            }
                        }
                    }
                }

                const userId = localStorage.getItem('userId');
                const reqData = {
                    equipmentId: values.equipmentId,
                    equipmentMaintainPositionAddDTOList: positionList,
                    equipmentMaintainWorkAddDTOList: workList.map(item => {
                        return {
                            ...item,
                            maintainStartTime: formatTime(item.maintainStartTime),
                            maintainEndTime: formatTime(item.maintainEndTime),
                        };
                    }),
                    id: values.id,
                    isStop: values.isStop,
                    maintainCost: values.maintainCost,
                    maintainEndTime: formatTime(values.maintainEndTime),
                    maintainLevel: values.maintainLevel,
                    maintainStartTime: formatTime(values.maintainStartTime),
                    maintainStatus: values.maintainStatus,
                    maintainTeamId: values.maintainTeamId,
                    maintainTreatmentId: values.maintainTreatmentId,
                    shutdownDuration: values.shutdownDuration,
                    userId: userId ? Number(userId) : null,
                    wastedTime: values.wastedTime,
                    workDescription: values.workDescription,
                    outsource: values.outsource,
                };
                // console.log(reqData); return;

                await post(euqApplicationName + '/equipmentMaintain/saveEquipmentMaintain', { data: reqData }, true);
                message.info('保存成功');
                history.replace('/MaintenanceWorkOrder');
            } catch (err) {
                err && console.error(err);
            }
        })();
    }, []);

    const handleCancelClick = useCallback(() => {
        history.goBack();
    }, []);

    const getCurrentTime = useCallback(async () => {
        const res = await get(euqApplicationName + '/equipmentMaintain/getCurrentTime');
        return res.data.time;
    }, []);

    useEffect(() => {
        if (id) {
            setMode('edit');
            (async () => {
                try {
                    const res = await get(euqApplicationName + '/equipmentMaintain/findEquipmentMaintain', { params: { id } });
                    if (res && res.data && res.data.length === 1) {
                        setForm1Data(res.data[0]);
                        setIsDataLoading(false);
                    } else {
                        Modal.error({
                            title: '未找到该工单',
                        });
                    }
                } catch (err) {}
            })();
        } else {
            setIsDataLoading(false);
        }
    }, []);

    return (
        <div>
            <h3>{viewTitle[mode]}</h3>
            <Card size="small" style={{ position: 'relative' }}>
                <Form1Wrap wrappedComponentRef={form1Ref} data={form1Data} />
                {isDataLoading && (
                    <div className="x-cover-loading2">
                        <Spin size="large" />
                    </div>
                )}
            </Card>
            <div style={{ marginTop: 15 }}>
                <Button type="primary" style={{ marginRight: 5 }} disabled={isDataLoading} onClick={handleSubmitClick}>保存</Button>
                <Button onClick={handleCancelClick}>取消</Button>
            </div>
        </div>
    );
}

export default MaintenanceWorkOrderDetail;
